package com.android.qjpmc.application_module.activity;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.android.qjpmc.R;
import com.android.qjpmc.application_module.home.model.StationDataModel;
import com.android.qjpmc.manager.LocationAMapManager;
import com.android.qjpmc.widget.SystemBarTintManagerHelper;
import com.android.qjpmc.widget.retrofithelper.rxsubscriber.CommonObserver;
import com.android.qjpmc.widget.utils.ToastUtils;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class SensorDataActivity extends AppCompatActivity implements SensorEventListener {

    private SensorManager sensorManager;
    private Sensor pressureSensor, accelerometerSensor, magnetometerSensor;

    private TextView gyroscopeData, locationData, altitudeData;
    private Button startButton, stopButton;
    private Handler handler = new Handler();
    private boolean isCollecting = false;
    String deviceCode, companyCode, groupId;
    private RadioGroup radioGroup;

    // 存储最新的陀螺仪数据
    private double gyroX = 0, gyroY = 0, gyroZ = 0;
    float[] gravity;
    float[] geomagnetic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sensor_data);

        SystemBarTintManagerHelper.getInsatance().initStateBar(this, R.color.color_244395, false, true);
        deviceCode = getIntent().getStringExtra("deviceCode");
        companyCode = getIntent().getStringExtra("companyCode");
        groupId = getIntent().getStringExtra("groupId");
        radioGroup = findViewById(R.id.radioGroup);

        // 初始化视图
        gyroscopeData = findViewById(R.id.gyroscope_data);
        locationData = findViewById(R.id.location_data);
        altitudeData = findViewById(R.id.altitude_data);
        startButton = findViewById(R.id.start_button);
        stopButton = findViewById(R.id.stop_button);

        // 获取传感器服务
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        // 获取陀螺仪传感器
        if (sensorManager != null) {
            accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            magnetometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
            pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        }


        // 设置开始按钮的点击事件
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startCollectingData();
            }
        });

        // 设置暂停按钮的点击事件
        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopCollectingData();
            }
        });
    }

    double amapLocationAltitude = 0;
    double altitude = 0;
    double amapLocationLatitude = 0;
    double amapLocationLongitude = 0;

    private void startCollectingData() {
        LocationAMapManager.getInstance().initLocation(this, new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (isCollecting) {
                    if (amapLocation != null) {
                        if (amapLocation.getErrorCode() == 0) {
                            Logger.d("sensor values=== location success==="
                                    + amapLocation.getLatitude() + "==="
                                    + amapLocation.getLongitude() + "===" + amapLocation.getAltitude());
                            locationData.setText("Latitude: " + amapLocation.getLatitude() + "\nLongitude: " + amapLocation.getLongitude());
                            if (amapLocation.getAltitude() != 0) {
                                amapLocationAltitude = amapLocation.getAltitude();
                                altitude = amapLocation.getAltitude();
                                altitudeData.setText("Altitude: " + amapLocation.getAltitude());
                            }
                            amapLocationLatitude = amapLocation.getLatitude();
                            amapLocationLongitude = amapLocation.getLongitude();
                        } else {
                            //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                            Logger.d("sensor values===location error==="
                                    + amapLocation.getErrorCode() + ", errInfo:"
                                    + amapLocation.getErrorInfo());
                        }
                    }
                }
            }
        });
        if (!isCollecting) {
            isCollecting = true;
            handler.postDelayed(sendDataRunnable, 2000); // 5秒后调用sendDataToNet方法
        }
        if (accelerometerSensor != null) {
            sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_UI);
        }
        if (magnetometerSensor != null) {
            sensorManager.registerListener(this, magnetometerSensor, SensorManager.SENSOR_DELAY_UI);
        }
        if (pressureSensor != null) {
            sensorManager.registerListener(SensorDataActivity.this, pressureSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    private void stopCollectingData() {
        if (isCollecting) {
            sensorManager.unregisterListener(this);
            handler.removeCallbacks(sendDataRunnable);
            isCollecting = false;
        }
    }

    // 处理传感器数据变化
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_PRESSURE) {
            if (amapLocationAltitude <= 0) {
                float pressure = event.values[0];
                altitude = calculateAltitude(pressure);
                altitudeData.setText("Altitude: " + String.format(Locale.getDefault(), "%.2f米", altitude));
            }
        } else {

            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                gravity = event.values;
            } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                geomagnetic = event.values;
            }
            if (gravity != null && geomagnetic != null) {
                float[] R = new float[9];
                float[] I = new float[9];
                boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
                if (success) {
                    float[] orientation = new float[3];
                    SensorManager.getOrientation(R, orientation);
                    // orientation[0] 是方位角（Z轴旋转角度）
                    // orientation[1] 是俯仰角（X轴旋转角度）
                    // orientation[2] 是滚动角（Y轴旋转角度）
                    gyroZ = (float) Math.toDegrees(orientation[0]);
                    gyroX = (float) Math.toDegrees(orientation[1]);
                    gyroY = (float) Math.toDegrees(orientation[2]);
                    String data = "X: " + gyroX + "\nY: " + gyroY + "\nZ: " + gyroZ;
                    gyroscopeData.setText(data);
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // 处理传感器精度变化（此处不需要实现）
    }

    private float calculateAltitude(float pressure) {
        //   float altitude = (float) (44330 * (1 - Math.pow(pressure / SensorManager.PRESSURE_STANDARD_ATMOSPHERE, 1 / 5.255)));
        float altitude = SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, pressure);
        //  float altitude = (float) ((1 - Math.pow((double) (pressure / 1013.25), (double) (1 / 5.265))) * 44300);

        return altitude;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 如果正在收集数据，暂停收集
        stopCollectingData();
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isCollecting) {
           // startCollectingData();
        }
        // 可以根据需要重新开始收集
    }

    // 定义一个Runnable，每5秒发送一次数据
    private final Runnable sendDataRunnable = new Runnable() {
        @Override
        public void run() {
            sendDataToNet();
            handler.postDelayed(this, 2000); // 再次设置5秒后调用sendDataToNet方法
        }
    };

    //  发送数据的方法
    private void sendDataToNet() {
        Logger.d("Sending data to net: X=" + gyroX + ", Y=" + gyroY + ", Z=" + gyroZ);
      /*  if (gyroX <= 0 || gyroY <= 0 || gyroZ <= 0 || amapLocationLongitude <= 0 || amapLocationLatitude <= 0 || amapLocationAltitude <= 0) {
            return;
        }*/
        int radioButtonID = radioGroup.getCheckedRadioButtonId();
        List<Map<String, Object>> list = new ArrayList<>();
        if (radioButtonID == R.id.radioButton1) {
            list.add(addRealTimeMap(companyCode + ".install_unit.x", amapLocationLongitude + ""));
            list.add(addRealTimeMap(companyCode + ".install_unit.y", amapLocationLatitude + ""));
            list.add(addRealTimeMap(companyCode + ".install_unit.z", altitude + ""));

            list.add(addRealTimeMap(companyCode + ".install_unit.angle_x", gyroX + ""));
            list.add(addRealTimeMap(companyCode + ".install_unit.angle_y", gyroY + ""));
            list.add(addRealTimeMap(companyCode + ".install_unit.angle_z", gyroZ + ""));
        } else {
            list.add(addRealTimeMap(deviceCode + ".x", amapLocationLongitude + ""));
            list.add(addRealTimeMap(deviceCode + ".y", amapLocationLatitude + ""));
            list.add(addRealTimeMap(deviceCode + ".z", altitude + ""));

            list.add(addRealTimeMap(deviceCode + ".angle_x", gyroX + ""));
            list.add(addRealTimeMap(deviceCode + ".angle_y", gyroY + ""));
            list.add(addRealTimeMap(deviceCode + ".angle_z", gyroZ + ""));
        }

        StationDataModel.setDataRealtime(list).subscribe(new CommonObserver<Object>() {
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                ToastUtils.showShort("数据上传成功");

            }
        });
    }

    private Map<String, Object> addRealTimeMap(String key, String value) {
        Map<String, Object> realTimeMap = new HashMap<>();
        realTimeMap.put("value", value);
        realTimeMap.put("point_code", key);
        return realTimeMap;
    }
}
